import datetime
import json
import time

from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from rest_framework.decorators import api_view

from HelloWorld.experimentDetail import getRegion, getConstellation, getStationByExpId, getConstellationGroup
from TestModel import models
from django.core import serializers
from django.utils import timezone


def login(request):
    body = json.loads(request.body.decode('utf-8'))
    account = body["account"]
    password = body["password"]
    user = models.User.objects.filter(account=account).get()
    print(user)
    if user.password == password:
        result = {
            "errorCode": 200,
            "userId": user.id,
            "authToken": 1
        }
    else:
        result = {
            "errorCode": 0,
            "errorMsg:": "密码不正确"
        }
    return JsonResponse(result, safe=False)


def register(request):
    body = json.loads(request.body.decode('utf-8'))
    account = body["account"]
    email = body["email"]
    password = body["password"]
    models.User.objects.create(account=account,
                               password=password,
                               email=email,
                               status=1)
    result = {
        "errorCode": 200,
    }
    return JsonResponse(result, safe=False)


@api_view(['GET'])
def getExperimentList(request, user_id):
    groups_select = models.UserGroup.objects.filter(userId=user_id)
    groups = json.loads(serializers.serialize("json", groups_select))
    group_list = []
    for group in groups:
        group_temp = {
            "groupName":group["fields"]["name"],
            "groupId":group["pk"]
        }
        experiment_select = models.Experiment.objects.filter(groupId=group["pk"])
        experiments = json.loads(serializers.serialize("json", experiment_select))
        experiment_list = []
        for experiment in experiments:
            experiment_temp = experiment["fields"]
            experiment_temp["id"] = experiment["pk"]
            experiment_list.append(experiment_temp)
        group_temp["experiments"] = experiment_list
        # 这里只有实验组的情况，没有实验详情
        group_list.append(group_temp)
    result = {
        "errorCode": 200,
        "data": group_list
    }
    return JsonResponse(result, safe=False)


def createGroup(request):
    body = json.loads(request.body.decode('utf-8'))
    groupName = body["groupName"]
    userId = body["userId"]
    models.UserGroup.objects.create(
        name=groupName,
        userId=userId,
        createTime=timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
        updateTime=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
    )
    result = {
        "errorCode": 200,
        "errorMsg": "创建成功"
    }
    return JsonResponse(result, safe=False)

def modifyExperiment(request):
    body = json.loads(request.body.decode('utf-8'))
    models.Experiment.objects.create(
        startTimeStampMs=body["startTimeStampMs"],
        groupId=body["groupId"],
        start=body["start"],
        h3Cr=5,
        endTimeStampMs=body["endTimeStampMs"],
        openTime=datetime.datetime.now().timestamp(),
        experimentName=body["experimentName"],
        calculateStatus=0,
        internalIdMax = 0,
        topSharding=1,
        topTaskNum=0,
        info = body["info"],
        propLossType ='[525,618,676,840]',
        topCalcType =1,
        modified = 1,
        step=60
    )
    createExperiment=models.Experiment.objects.filter().order_by('createTimeStampMs').reverse()[:1]
    resultCreateExperiment = json.loads(serializers.serialize("json", createExperiment))
    id=resultCreateExperiment[0]["pk"]
    print(id)
    models.ExperimentStatus.objects.create(
        experimentId=id,
        type=0,
        calculateStatus=0,
        configStatus=0,
        runningStatus=0,
    )
    result = {
        "errorCode": 200,
        "errorMsg": "创建成功"
    }
    return JsonResponse(result, safe=False)

@api_view(['POST'])
def deleteExperiment(request):
    body = json.loads(request.body.decode('utf-8'))
    experimentId = body["experimentId"]
    models.Experiment.objects.filter(id=experimentId).delete()
    models.ExperimentStatus.objects.filter(experimentId=experimentId).delete()
    result = {
        "errorCode": 200
    }
    return JsonResponse(result, safe=False)

def modifyGroup(request):
    body = json.loads(request.body.decode('utf-8'))
    models.UserGroup.objects.filter(id=body["groupId"]).update(
        name=body["groupName"],
        userId=body["userId"],

        updateTime=timezone.now().strftime("%Y-%m-%d %H:%M:%S")
    )
    result = {
        "errorCode": 200,
        "errorMsg": "修改实验组成功"
    }
    return JsonResponse(result, safe=False)

def deleteGroup(request):
    body = json.loads(request.body.decode('utf-8'))
    models.UserGroup.objects.filter(Q(id=body["groupId"]) & Q(userId=body["userId"])).delete()
    result = {
        "errorCode": 200,
        "errorMsg": "删除实验组成功"
    }
    return JsonResponse(result, safe=False)